from html_00_common_header import generate_common_header
from html_01_common_footer import generate_common_footer


def handle_root_path(self):
    self.send_response(200)
    self.send_header('Content-type', 'text/html; charset=utf-8')
    self.end_headers()
    self.wfile.write((generate_common_header("选择题型", "1") +
                      generate_body(self) +
                      generate_common_footer()).encode('utf-8'))


def generate_body(self):
    return (get_dynamic_stars() +
            get_style() +
            '<h1 style="color: #66ccff; text-shadow: 0 0 15px #66ccff; text-align: center;">请选择要练习的题型</h1>' +
            get_question_type_list(self))

def get_dynamic_stars():
    return """
<style>
body {
    background: radial-gradient(ellipse farthest-corner at center, #031633 60%, #000000 100%);
}
/* 动态生成的星星样式（新增移动动画） */
.dynamic-star {
    position: absolute;
    width: 2px;
    height: 2px;
    background: white;
    border-radius: 50%;
    /* 同时应用闪烁和移动动画 */
    animation: twinkle 1s infinite, moveStars 5s linear infinite;
}

@keyframes twinkle {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 0.2;
    }
    100% {
        opacity: 1;
    }
}

@keyframes moveStars {
    0% {
        transform: translateX(0);
    }
    100% {
        transform: translateX(var(--move-x)); /* 使用自定义属性控制移动距离 */
    }
}

/* 彗星效果，改为不规则球状模拟星体 */
.comet {
    position: absolute;
    width: 20px;
    height: 20px;
    background: radial-gradient(circle at 50% 50%, #66ccff, #031633);
    border-radius: 50%;
    filter: drop-shadow(0 0 10px #66ccff);
    animation: cometTrail 1s linear forwards, cometExplode 0.8s 0.2s forwards;
    transform-origin: 50% 50%;
    /* 添加不规则形状 */
    clip-path: polygon(
        50% 0%,
        61% 35%,
        98% 35%,
        68% 57%,
        79% 91%,
        50% 70%,
        21% 91%,
        32% 57%,
        2% 35%,
        39% 35%
    );
}

@keyframes cometTrail {
    0% {
        transform: translateY(0) translateX(0) scale(1);
        opacity: 1;
    }
    100% {
        transform: translateY(500px) translateX(calc(-200px + (400px * var(--random-x)))) scale(0);
        opacity: 0;
    }
}

@keyframes cometExplode {
    0% {
        box-shadow: 0 0 0 0 rgba(102, 204, 255, 0.5);
    }
    100% {
        box-shadow: 0 0 50px 50px rgba(102, 204, 255, 0);
    }
}
</style>
<script>
// 新增：动态生成星星的逻辑
function generateDynamicStars() {
    // 移除旧星星（避免重复生成）
    document.querySelectorAll('.dynamic-star').forEach(star => star.remove());

    const starCount = 300; // 调整数量控制密度
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;

    for (let i = 0; i < starCount; i++) {
        const star = document.createElement('div');
        star.className = 'dynamic-star';

        // 随机生成覆盖全屏的位置
        const x = Math.random() * screenWidth;
        const y = Math.random() * screenHeight;

        star.style.left = `${x}px`;
        star.style.top = `${y}px`;

        // 随机动画延迟，让闪烁更自然
        star.style.animationDelay = `${Math.random() * 5}s`;

        document.body.appendChild(star);
    }
}

// 页面加载时生成星星
window.addEventListener('load', generateDynamicStars);
// 窗口调整时重新生成
window.addEventListener('resize', generateDynamicStars);

// 原有的彗星效果逻辑（保持不变）
let lastX = 0;
let lastY = 0;

document.addEventListener('mousemove', function(event) {
    const comet = document.createElement('div');
    comet.className = 'comet';
    const x = event.clientX;
    const y = event.clientY;

    // 计算鼠标移动方向
    const dx = x - lastX;
    const dy = y - lastY;

    // 随机生成 -1 到 1 之间的数，用于水平偏移
    const randomX = (Math.random() * 2 - 1);
    comet.style.setProperty('--random-x', randomX);

    // 计算与鼠标移动相反的方向，并增加随机角度偏移
    const randomAngleOffset = (Math.random() - 0.5) * 30; // 正负 15 度的随机偏移
    const angle = Math.atan2(-dy, -dx) * (180 / Math.PI) + randomAngleOffset + 90; // 加上 90 度让其向下

    comet.style.left = x + 'px';
    comet.style.top = y + 'px';
    comet.style.transform = `rotate(${angle}deg)`;

    document.body.appendChild(comet);

    // 动画结束后移除彗星元素
    comet.addEventListener('animationend', function() {
        comet.remove();
    });

    lastX = x;
    lastY = y;
});
</script>
"""


def get_question_type_list(self):
    html = '<div class="question-type-container">'
    for q_type in ["判断题", "单选题", "多选题"]:
        type_questions = [q for q in self.questions if q['题目类型'] == q_type]
        min_num = min(q['题号'] for q in type_questions)
        max_num = max(q['题号'] for q in type_questions)
        existing_numbers = [q['题号'] for q in type_questions]
        missing_numbers = [num for num in range(min_num, max_num + 1) if num not in existing_numbers]
        missing_info = ""
        if missing_numbers:
            missing_info = f'<span style="color: #ff0000;"> (缺少题号: {", ".join(map(str, missing_numbers))})</span><br>'
        # 题目数量显示
        html += f'''
<a href="/select_range?type={q_type}" class="question-type-button">
    {get_button_icon(q_type)}{q_type}
    <span class="question-count">（共{len(type_questions)}题）</span>
</a>
{missing_info}
'''
    html += get_fill_blank_button(self)
    html += get_reset_stat_button()
    html += get_last_question_type()
    html += '</div>'
    return html

def get_fill_blank_button(self):
    return f'''
<a href="/fill_blank" class="question-type-button">
    {get_button_icon('填空题')}填空题
    <span class="question-count">（共{len(self.questionFilesOfFill)}题）</span>
</a>
'''

def get_button_icon(q_type):
    # 新增：根据题型生成图标HTML
    if q_type == "判断题":
        icon = '<span class="type-icon judgment-icon"></span>'
    elif q_type == "单选题":
        icon = '<span class="type-icon single-icon"></span>'
    elif q_type == "多选题":
        icon = '<span class="type-icon multiple-icon"></span>'
    elif q_type == "填空题":
        icon = '<span class="type-icon fill-blank-icon"></span>'
    else:
        icon = ''
    return icon


def get_style():
    return '''
<style>
body {
    overflow: hidden;
}

.question-type-button {
    display: inline-flex; /* 保留 flex 布局 */
    align-items: center; /* 垂直居中对齐 */
    flex-direction: column; /* 垂直布局让数量显示在下方 */
    gap: 5px; /* 图标/文字与数量的间距 */
    padding: 12px 24px;
    background-color: rgba(102, 204, 255, 0.2);
    color: #66ccff;
    border: 2px solid #66ccff;
    border-radius: 5px;
    text-decoration: none;
    font-weight: bold;
    transition: all 0.3s ease;
    box-shadow: 0 0 10px rgba(102, 204, 255, 0.3), 0 0 20px rgba(102, 204, 255, 0.1) inset;
}

/* 新增：题目数量样式 */
.question-count {
    font-size: 0.9em;
    color: #88d9ff;
    font-weight: normal;
}

.question-type-button:hover {
    background-color: #66ccffc9;
    color: #000;
    transform: translateY(-3px);
    box-shadow: 0 0 20px rgba(102, 204, 255, 0.6), 0 0 30px rgba(102, 204, 255, 0.3) inset;
}

/* 保留其他图标样式 */
.type-icon {
    width: 20px;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.judgment-icon::after {
    content: "✓✗";
    font-size: 1.2em;
    color: #66ccff;
}

.single-icon::after {
    content: "●";
    font-size: 1.4em;
    color: #66ccff;
}

.multiple-icon::after {
    content: "✓";
    font-size: 0.9em;
    color: #66ccff;
    border: 2px solid #66ccff;
    border-radius: 3px;
    padding: 0 2px;
}

.fill-blank-icon::after {
    content: "⌨";
    font-size: 1.4em;
    color: #66ccff;
}

.question-type-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
    align-items: center;
    position: relative;
    z-index: 1;
    justify-content: center;
}
</style>
'''


def get_reset_stat_button():
    return '''
<style>
.reset-stats-button {
    padding: 12px 24px;
    background-color: rgba(255, 0, 0, 0.2);
    color: #ff0000;
    border: 2px solid #ff0000;
    border-radius: 5px;
    text-decoration: none;
    font-weight: bold;
    transition: all 0.3s ease;
    box-shadow: 0 0 10px rgba(255, 0, 0, 0.3), 0 0 20px rgba(255, 0, 0, 0.1) inset;
    margin-top: 20px;
}
.reset-stats-button:hover {
    background-color: rgba(255, 0, 0, 0.8);
    color: #fff;
    transform: translateY(-3px);
    box-shadow: 0 0 20px rgba(255, 0, 0, 0.6), 0 0 30px rgba(255, 0, 0, 0.3) inset;
}
</style>
<button id="reset-stats-button" class="reset-stats-button">重置答题统计</button>
<script>
    document.getElementById('reset-stats-button').addEventListener('click', function() {
        if (confirm('确定要重置答题统计吗？')) { 
            fetch('/reset_stats', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            })
            .then(response => {
                if (response.ok) {
                    alert('统计数据已重置！');
                } else {
                    alert('重置失败，请重试！');
                }
            })
            .catch(error => {
                console.error('重置统计数据失败:', error);
                alert('网络错误，重置失败！');
            });
        }
    });
</script>
'''

def get_last_question_type():
    return '''
<button id="question-type-button" class="question-type-button">上次做的题目</button>
<script>
    document.getElementById('question-type-button').addEventListener('click', function() {
        fetch('/get_last_question')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.hasOwnProperty('question_url')) {
                    window.location.href = data.question_url;
                } else {
                    alert('未找到最后一道题的信息');
                }
            })
            .catch(error => {
                console.error('获取最后一道题失败:', error);
                alert('获取最后一道题失败，请重试！');
            });
    });
</script>
'''